package com.creatation.prototype;

import java.util.HashMap;
import java.util.Map;

public class MyMybaties {
    private Map<String,User> userCache = new HashMap<>();
//    从数据库查
    public User getUser(String username)
            throws Exception {
        User user = null;
//        缓存中没有
//        containsKey()如果此映射包含指定键的映射，则返回 true
//        是否包含当前key

        if (!userCache.containsKey(username)){
//         查询数据库
            user = getUserFromDb(username);
        }else {
            user= userCache.get(username);
            System.out.println("从这个对象中拿到的是："+user);
//            从这个对象快速得到一个克隆体
//            (克隆重点)原型模式
            user = (User) user.clone();
        }
        return user;
    }

    private User getUserFromDb(String username)
            throws CloneNotSupportedException {
        System.out.println("从数据库中查到"+username);
        User user = new User();
        user.setUsername(username);
        user.setAge(18);
        userCache.put(username, (User) user.clone());
        return user;

    }
}
